package com.wondersgroup.fjzlpt.org.service.impl.tdgl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.ExcelOrWordUtils;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QyxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdjbxxDao;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdrjDao;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdryDao;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdshDao;
import com.wondersgroup.fjzlpt.org.dao.inter.yljgry.YljgryDAO;
import com.wondersgroup.fjzlpt.org.service.inter.tdgl.TdglService;
import static com.wondersgroup.fjzlpt.org.util.ProjectParams.ystdzRole;

@Service
public class TdglServiceImpl implements TdglService{

	@Autowired
	private TdjbxxDao tdjbxxDao;
	
	@Autowired
	private TdryDao tdryDao;
	
	@Autowired 
	private TdrjDao tdrjDao;
	
	@Autowired
	private TdshDao tdshDao;
	
	@Autowired
	private YljgryDAO yljgryDAO;

	@Autowired
	private QyxxDAO qyxxDAO;

	
	@Override
	public JSONArray queryAll(Map<String, String> map) {
		return null;
	}

	@Override
	public JSONObject queryPage(Map<String, String> map) {
		return tdjbxxDao.queryPage(map);
	}
	
	/**
	 * 判断是否存在相同的团队名称
	 * @return
	 */
	public JSONObject checkSaveName(Map<String, String> map){
		return tdjbxxDao.checkSaveName(map);
	}

	@Override
	public JSONObject save(Map map) {
		ResultObject ro = new ResultObject();
		
		try {
			String method   = map.remove("method").toString();
			map.put("YLJGID", tdjbxxDao.getDztPtjgid(map.get("xTdzid").toString()));//YLJGID为当前团队长所在平台的PTJGID
			
			JSONObject tdxxObj = tdjbxxDao.checkSaveName(map);
			if(!tdxxObj.isEmpty()){
				ro.changeFaultState("存在相同的团队名称，请重新输入！");
				return (JSONObject) JSON.toJSON(ro);
			}else{
					if("add".equals(method)){
						this.insert(map,ro);
					}else{
						map.remove("XJR");
						this.update(map,ro);
					}
					//添加审核申请记录
					Date nowTime = new Date();
					map.put("SHID", UUID.randomUUID().toString());
					map.put("SHTJSJ", nowTime);
					if("1".equals(map.get("laterUpdate"))){
						//后期正常团队维护
						ro.setInfo("success", "保存成功！");
					}else if("1".equals(map.get("SHZT"))){
						tdshDao.insert(map);
						ro.setInfo("success", "您创建的团队已提交到医院管理员审核，请静待审核结果！");
					}else if("2".equals(map.get("SHZT"))){
						map.put("SHSJ", nowTime);
						tdshDao.insert(map);
						String tdzRoleId=tdryDao.queryTdzUserRoleByTdzid((String)map.get("xTdzid"));
						if(!ystdzRole.equals(tdzRoleId)){
							tdryDao.updateTdzRole(map.get("xTdzid").toString(), ystdzRole);
						}

						ro.setInfo("success", "新增团队成功！");
					}
			}
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000701","审核表数据保存失败！");
		}
		return (JSONObject) JSON.toJSON(ro);
	}
	
	/**
	 * 团队提交审核
	 * @return
	 */
	public JSONObject submitCheck(Map map){
		ResultObject ro = new ResultObject();
		
		try {
			map.put("SHZT", "1");
			Date date = FormatDate.getDateY_M_D(map.get("CJSJ").toString());
			map.put("CJSJ", date);
			tdjbxxDao.updateForPrimaryKey(map);
			
			//添加审核申请记录
			map.put("SHID", UUID.randomUUID().toString());
			map.put("SHTJSJ", new Date());
			tdshDao.insert(map);
			ro.setInfo("success", "您创建的团队已提交到医院管理员审核，请静待审核结果！");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000702","审核表数据保存失败！");
		}
		return (JSONObject) JSON.toJSON(ro);
	}

	@Override
	public JSONObject delete(Map map) {
		ResultObject ro = new ResultObject();
		try {
			map.put("YLTDID", map.get("TDID"));
			map.put("QYLX", "01");
			JSONObject qyObj = qyxxDAO.queryOne(map);
			if(qyObj.isEmpty()){
				map.remove("CJSJ");
				map.remove("TDMC"); //中英文混合会出现乱码

				Date nowTime = new Date();
				map.put("JSSJ", nowTime);//解散时间
				tdjbxxDao.updateForPrimaryKey(map);
				
				map.put("CZGYSM", "解散团队");
				map.put("JLSJ", nowTime);
				tdrjDao.insert(map);
				
				ro.setInfo("success", "解散成功");
				
			}else{
				ro.changeFaultState("团队还有未完成的服务对象，暂时不可解散！");
			}
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000703","解散团队失败");
		}
		return (JSONObject) JSON.toJSON(ro);
	}
	
	private void insert(Map map,ResultObject ro){
		
		String addTDCY = map.remove("addTDCY").toString();
		map.remove("yTdzid");
		
		String TDID = UUID.randomUUID().toString();
		map.put("TDID", TDID);
		
		Date nowTime = new Date();
		map.put("CJSJ", nowTime);
		try {
			tdjbxxDao.insert(map);
			//新增团队成员
			JSONArray addTDCYArr = JSONArray.parseArray(addTDCY);
			List<Map> tdcyList = this.formatNewTdcy(addTDCYArr, TDID, nowTime);
			tdryDao.insertBatch(tdcyList);
			//团队日记
			Map mapBase = new HashMap();
			mapBase.put("TDID", TDID);
			mapBase.put("JGID", map.get("YLJGID"));
			mapBase.put("CZRID", map.get("CZRID"));
			mapBase.put("CZGYSM", "新增成员");
			mapBase.put("JLSJ",nowTime);
			List<Map> tdrjList = this.formatTdrj(addTDCYArr, mapBase,"add");
			tdrjDao.insertBatch(tdrjList);
			ro.setInfo("success","新增团队成功！");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000704","新增团队失败");
		}
	}
	
	private void update(Map<String, String> map,ResultObject ro){
		String addTDCY = map.remove("addTDCY");
		String deleteTDCY = map.remove("deleteTDCY");
		String changeTDCY = map.remove("changeTDCY");
		String yTdzid = map.remove("yTdzid");
		//String xTdzid = map.get("xTdzid");
		String TDID = map.get("TDID");
		
		Date nowTime = new Date();
			   
		try {
			tdjbxxDao.updateForPrimaryKey(map);
			
			JSONArray deleteTDCYArr = JSONArray.parseArray(deleteTDCY);
			JSONArray addTDCYArr = JSONArray.parseArray(addTDCY);
			JSONArray changeTDCYArr = JSONArray.parseArray(changeTDCY);

			//团队日记
			Map mapBase = new HashMap<String,Object>();
			mapBase.put("TDID", TDID);
			mapBase.put("JGID", map.get("YLJGID"));
			mapBase.put("CZRID", map.get("CZRID"));
			mapBase.put("CZGYSM", "新增成员");
			mapBase.put("JLSJ",nowTime);
			List<Map> addTdrjList = this.formatTdrj(addTDCYArr, mapBase,"add");
			
			mapBase.put("CZGYSM", "删除成员");
			List<Map> deleteTdrjList = this.formatTdrj(deleteTDCYArr, mapBase,"del");
			addTdrjList.addAll(deleteTdrjList);
			
			//是否更改团队长
			if(!StringUtils.isEmpty(yTdzid)){
				/*map.put("USERID", yTdzid);
				map.put("TDJS", "2");
				tdryDao.updateTDJS(map);*/
				
				mapBase.put("YSID", yTdzid);
				mapBase.put("CZGYSM", "团队长改为普通成员");
				mapBase.put("JLSJ",getNearTime(-1000));
				addTdrjList.add(mapBase);
				
				/*map.put("USERID", xTdzid);
				if(tdryDao.isExist(map)){ //如果现任团队长是原团队队员，则更新记录
					map.put("TDJS", "1");
					tdryDao.updateTDJS(map);
					
					Map<String, Object> xdzMap = new HashMap<String,Object>();
					xdzMap.putAll(mapBase);
					xdzMap.put("YSID", xTdzid);
					xdzMap.put("CZGYSM", "设为团队长");
					xdzMap.put("JLSJ", getNearTime(-500));
					addTdrjList.add(xdzMap);
				}*/
			}
			
			//删除团队成员()
			if(deleteTDCY!=null && deleteTDCYArr.size()>0){
				tdryDao.deleteTdrys(TDID, deleteTDCYArr);
			}
			//普通成员与团队助手的互相转换
			for(int i=0;i<changeTDCYArr.size();i++){
				JSONObject item = changeTDCYArr.getJSONObject(i);
				Map<String,String> itemMap = new HashMap<String,String>();
				itemMap.put("TDID",TDID);
				itemMap.put("TDJS",item.getString("TDJS"));
				itemMap.put("USERID",item.getString("USERID"));
				tdryDao.updateTDJS(itemMap);

				Map<String, Object> rjMap = new HashMap<String,Object>();
				rjMap.putAll(mapBase);
				rjMap.put("YSID", item.getString("USERID"));
				String TDJS = item.get("TDJS").toString();
				if("1".equals(TDJS)){
					rjMap.put("CZGYSM", "设为团队长");
				}else if("2".equals(TDJS)){
					rjMap.put("CZGYSM", "设为普通成员");
				}else{
					rjMap.put("CZGYSM", "设为团队助手");
				}
				rjMap.put("JLSJ", new Date());
				addTdrjList.add(rjMap);
			}
			//新增团队成员
			List<Map> tdcyList = this.formatNewTdcy(addTDCYArr, TDID, nowTime);
			tdryDao.insertBatch(tdcyList);

			tdrjDao.insertBatch(addTdrjList);
			ro.setInfo("success", "保存成功！");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000704","维护团队失败");
		}
	}
	
	
	/**
	 * 组装新团队成员数据
	 * @param tdcyArr
	 * @param TDID
	 * @param RTSJ
	 * @return
	 */
	private List<Map> formatNewTdcy(JSONArray tdcyArr,String TDID,Object RTSJ){
		List<Map> result = new ArrayList<Map>();
		
		for (int i = 0; i < tdcyArr.size(); i++) {
			JSONObject item = tdcyArr.getJSONObject(i);
			Map map = new HashMap();
			map.put("TDID", TDID);
			map.put("USERID", item.getString("USERID"));
			map.put("TDJS", item.getString("TDJS"));
			map.put("RTSJ", RTSJ);
			
			result.add(map);
		}
		
		return result;
	}
	
	/**
	 * 组装团队日记数据
	 * @param arr
	 * @param mapBase
	 * @return
	 */
	private List<Map> formatTdrj(JSONArray arr,Map<String, String> mapBase,String type){
		List<Map> result = new ArrayList<Map>();
		
		for (int i = 0; i < arr.size(); i++) {
			JSONObject item = arr.getJSONObject(i);
			Map<String,String> map = new HashMap<String,String>();
			map.putAll(mapBase);
			map.put("YSID", item.getString("USERID"));
			if("add".equals(type)){
				if("1".equals(item.getString("TDJS"))){
					map.put("CZGYSM", mapBase.get("CZGYSM")+",设为团队长");
				}else if("3".equals(item.getString("TDJS"))){
					map.put("CZGYSM", mapBase.get("CZGYSM")+",设为团队助手");
				}
			}
			result.add(map);
		}
		
		return result;
	}

	@Override
	public JSONArray queryTdcylbAll(Map<String, String> map) {
		return tdryDao.queryTdcylbAll(map);
	}

	/**
	 * 根据条件分页查询机构人员信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYljgryxxWithConditionByPage(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			result = tdjbxxDao.queryYljgryxxWithConditionByPage(map);
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000705","医生数据查询失败");
		}
		return result;
	}
	
	/**
	 * 根据名称模糊查询机构名称-分页查询
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYljgxxByPage(Map<String, String> map){
		return tdjbxxDao.queryYljgxxByPage(map);
	}

	/**
	 * 查询团队审核信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryTdshxx(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			result = tdshDao.queryTdshxx(map);
			result.put("state", true);
		} catch (Exception e) {
			result.put("info", "审核信息查询失败");
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000705","审核信息查询失败");
		}
		
		return result;
	}

	/**
	 * 分页查询团队日记
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryLogsByPage(Map<String, String> map) {
		return tdrjDao.queryLogsByPage(map);
	}
	
	/**
	 * 获取当前时间前后ms毫米的时间
	 * @param ms
	 * @return
	 */
	private Date getNearTime(int ms){
		Calendar c = new GregorianCalendar();
		Date date = new Date();
		c.setTime(date);//设置参数时间
		c.add(Calendar.MILLISECOND,ms);//把日期往后增加SECOND 秒.整数往后推,负数往前移动
		
		date=c.getTime(); //这个时间就是日期往后推一天的结果
		return date;
	}

	/**
	 * 审核团队信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject checkTdxx(Map map) {
		ResultObject ro = new ResultObject();
		
		map.put("SHSJ", new Date());
		
		try {
			tdshDao.updateForPrimaryKey(map);
			
			Object type = map.get("type");
			if("pass".equals(type)){
				map.put("SHZT", "2"); //审核通过
				map.put("TDZT", "1"); //团队可用
				String tdzUserId = tdryDao.queryTdzUseridByTdid(map.get("TDID").toString());
				String tdzRoleId=tdryDao.queryTdzUserRoleByTdzid(tdzUserId);
				if(!ystdzRole.equals(tdzRoleId)){
					tdryDao.updateTdzRole(tdzUserId, ystdzRole);
				}
			}else {
				map.put("SHZT", "3"); //审核不通过
			}
			tdjbxxDao.updateForPrimaryKey(map);
			ro.setInfo("success","审核成功");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000706","团队审核失败");
		}
		return (JSONObject)JSON.toJSON(ro);
	}
	
	/**
	 * 根据用户id查询医疗机构人员信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYljgryxxByUserid(Map<String, String> map){
		JSONObject result = new JSONObject();
		try {
			result = yljgryDAO.queryOne(map);
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000707","用户信息查询失败");
		}
		return result;
	}
	
	/**
	 * 查询医疗机构人员多点执业信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYljgryDdzy(Map<String, String> map){
		JSONObject result = new JSONObject();
		try {
			result.put("data", yljgryDAO.queryDdzy(map));
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000708","多点执业信息查询失败");
		}
		return result;
	}

	@Override
	public void downTdxxToExcel(Map<String, String> map,HttpServletRequest request, HttpServletResponse response) {
		JSONArray tdxxArr = tdjbxxDao.queryAll(map);
		//审核状态代码转中文
		JSONObject shztObj = JSONObject.parseObject("{'0':'暂存','1':'待审核','2':'正常','3':'审核不通过','4':'已解散'}");
		for (int i=0;i<tdxxArr.size();i++) {
			JSONObject item = tdxxArr.getJSONObject(i);
			item.put("SHZT_CN", shztObj.get(item.get("SHZT")));
		}
		//表头
		String titleStr = "{'TDMC':'团队名称','DZXM':'队长','XBMC':'性别','LXDH':'手机号码','CJSJ':'创建日期','TDCY':'团队成员','SHZT_CN':'当前状态'}";
		JSONObject title = JSONObject.parseObject(titleStr);
		tdxxArr.add(0, title);
		
		//排列循序
		List<String> titelField = new ArrayList<>();
		titelField.add("TDMC");
		titelField.add("DZXM");
		titelField.add("XBMC");
		titelField.add("LXDH");
		titelField.add("CJSJ");
		titelField.add("TDCY");
		titelField.add("SHZT_CN");
		ExcelOrWordUtils.downLoadExcelFile(tdxxArr, titelField ,"团队列表",request, response);
	}
	
	/**
	 * 分页查询团队信息到健康城市系统
	 * @param map {XZQHDM=xxx,YLJGDM=xxx,pageSize=xxx,pageNumber=xxx}
	 * @return
	 */
	public JSONObject queryTdxxByPageToJkcs(Map<String, String> map){
		return tdjbxxDao.queryTdxxByPageToJkcs(map);
	}
	
}
